<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\JasminumMenu\Controllers;

use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaFileSystemExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\GotchaSettingsQuery;
use GotchaDatabase\JasminumMenusQuery;

class DefaultController extends Controller {
    public function Download() {
        // Check current type
        if (!isset($_GET['type']) || empty($_GET['type'])) {
            GotchaErrorsExtension::throwError(new String('Brakujący argument.'));
            exit;
        }

        switch ($_GET['type']) {
            case 'footer':
                $menu = JasminumMenusQuery::create()
                            ->filterByType('footer')
                                ->findOneByIsActive(true);

                if (!$menu) {
                    GotchaErrorsExtension::throwError(new String('Żadne menu nie jest aktywne.'));
                    exit;
                }

                // Additionally retrieve path where files are stored
                $settings = GotchaSettingsQuery::create()
                                ->findOneByStrongName('PdfMenuDir');

                // Make sure that the file exists
                if (GotchaFileSystemExtension::CheckFileExistence(new String($menu->getFilename()), new String(GOTCHA_ROOT_DIR.$settings->getValue())) === false) {
                    GotchaErrorsExtension::throwError(new String('Plik nie istnieje.'.GOTCHA_ROOT_DIR.$settings->getValue().$menu->getFilename()));
                    exit;
                }

                // We have active menu, send a header to a browser
                header ('Content-Type: application/pdf');

                // Send a file
                readfile(GOTCHA_ROOT_DIR.$settings->getValue().$menu->getFilename());
                exit;
        }
    }
}